<template>
    <div class="framework1">
        <!--    全部表格-->
        <div class="framework2">

            <!--      上半部分表格-->
            <div>

                <div class="header">数据字典->法律列表</div>

                <div class="button_group">
                    <el-button type="primary" icon="DocumentAdd" v-if="permissionIsShow.add"
                        @click="addLaws()">新增法律</el-button>
                    <el-select v-model="searchType" clearable placeholder="搜索法律类型"
                        style="width: 250px;margin-left: 10px;margin-right: 10px">
                        <el-option v-for="type in lowsTypeList" :key="type" :label="type" :value="type" />
                    </el-select>
                    <!-- <el-input v-model="searchType" placeholder="搜索法律类型"
                        style="width: 250px;margin-left: 15px;margin-right: 15px" clearable></el-input> -->
                    <el-input v-model="searchName" placeholder="搜索法律名称" style="width: 250px;margin-right: 10px"
                        clearable></el-input>
                    <el-button type="primary" icon="Search" @click="searchLaws()">搜索</el-button>
                </div>

                <div style="height: calc(100vh - 134px)">
                    <el-table :data="lowsList" :header-cell-style="{ background: '#f4f3f9' }" highlight-current-row
                        style="width:100%; height: calc(100% - 68px); background:#f4f3f9" border>
                        <el-table-column align="center" prop="type" label="法律类型"></el-table-column>
                        <el-table-column align="center" prop="name" label="法律名称"></el-table-column>

                        <el-table-column align="center" prop="operate" label="操作" width="200" fixed="right"
                            v-if="permissionIsShow.edit || permissionIsShow.delete">
                            <template v-slot="scope">
                                <el-button type="primary" size="small" icon="Edit" v-if="permissionIsShow.edit"
                                    @click.native.stop="editRoleData(scope.row)">修改</el-button>
                                <el-button type="danger" size="small" icon="Delete" v-if="permissionIsShow.delete"
                                    @click.native.stop="deleteRoleData(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!--      分页1-->
                    <div class="footer">
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :page-sizes="[5, 10, 20]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="total">
                        </el-pagination>
                    </div>
                </div>
            </div>
        </div>
        <!-- 新增/编辑 弹窗 -->
        <el-dialog v-model="dialogFormVisible" :close-on-click-modal="false" :title="isEdit ? '修改' : '新增'"
            :before-close="closeAddLaws" width="900px">
            <el-form>
                <el-form-item>
                    <span>法律类型：</span>
                    <el-select v-model="lawsForm.type" class="law-type-select-style" filterable allow-create clearable
                        placeholder="例：【行政法规】" style="width: 150px;"
                        @change="(val) => handlelawTypeChange(lawsForm, val)"
                        @blur="handlelawTypeBlur(lawsForm, $event)" @clear="clearLawsFields(lawsForm, 'type')">
                        <el-option v-for="type in lowsTypeList" :key="type" :label="type" :value="type" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <span>法律名称：</span>
                    <el-input type="textarea" v-model="lawsForm.name" placeholder="例：《城市市容和环境卫生管理条例》"></el-input>
                </el-form-item>
            </el-form>


            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeAddLaws">取消</el-button>
                    <el-button type="primary" @click="saveLaws()">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import request from "@/utils/request";
import SIdentify from "@/views/SIdentify.vue";
export default {
    name: "Laws",
    components: { SIdentify },
    data() {
        return {
            searchType: "",
            searchName: "",

            lowsList: [], // 法律列表
            lowsTypeList: [], // 法律类型列表

            total: 0,
            pageSize: 10,
            pageNum: 1,

            dialogFormVisible: false, //新增弹窗控制
            isEdit: false, // 编辑标志


            lawsForm: {
                type: null, // 法律类型
                name: null, // 法律名称
            },
            // 登录用户信息
            loginUserInfo: {
                id: '',
                responsibleScope: '', //查询范围
                roleLevel: '', //角色等级
                unitId: '', //内设部门ID
                userRole: '', //角色ID
                permissions: [], // 按钮路径（数据库中的path）
            },
            // 按钮权限
            permissionIsShow: {
                add: false,
                edit: false,
                delete: false,
            },
        }
    },
    created() {
        const info = JSON.parse(localStorage.getItem("user"));
        this.loginUserInfo = {
            id: Number(info.id),
            responsibleScope: info.responsibleScope, //查询范围
            roleLevel: Number(info.roleLevel),
            unitId: Number(info.unitId),
            userRole: Number(info.userRole),
            permissions: info.permissions.filter(item => Number(item.menuId) === 33).map(item => item.path),
        }
        this.permissionIsShow = {
            add: this.loginUserInfo.permissions.includes('laws-add'),
            edit: this.loginUserInfo.permissions.includes('laws-edit'),
            delete: this.loginUserInfo.permissions.includes('laws-delete'),
        }
        this.load()
    },
    methods: {
        // 获取数据
        load() {
            this.gettableData()
            this.getLowsTypeList()
        },
        // 搜索
        searchLaws() {
            this.pageNum = 1;
            this.gettableData();
        },

        // 分页
        handleSizeChange(val) {
            this.pageSize = val;
            this.gettableData();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.gettableData();
        },
        // 获取法律列表数据
        getLowsTypeList() {
            request.get("/laws/getLawsType").then(res => {
                if (res.code == '200') {
                    this.lowsTypeList = res.data
                }
            })
        },

        // 查询数据
        gettableData() {
            request.get("/laws/page", {
                params: {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    type: this.searchType,
                    name: this.searchName,
                }
            }).then(res => {
                if (res.code == '200') {
                    this.lowsList = res.data.records
                    this.total = res.data.total
                }
            })
        },

        // 处理法律类型变化（下拉选择时触发）
        handlelawTypeChange(item, val) {
            item.type = val; // 更新类型
        },

        // 处理法律类型输入（失去焦点时触发）
        handlelawTypeBlur(item, event) {
            item.type = event.target.value;
            item.name = null;
        },

        // 新增法律
        addLaws() {
            this.dialogFormVisible = true
        },


        // 新增弹窗关闭
        closeAddLaws() {
            this.dialogFormVisible = false
            // 清空数据
            this.lawsForm = {
                type: null, // 法律类型
                name: null, // 法律名称
            }
        },
        // 验证表单
        isValidate(form) {
            // 定义规则
            const rules = {
                type: [{ required: true, message: '请输入法律类型', trigger: 'change' }],
                name: [{ required: true, message: '请输入法律名称', trigger: 'blur' }],
            }
            // 验证表单
            for (const key in rules) {
                if (rules.hasOwnProperty(key)) {
                    const rule = rules[key];
                    const value = form[key];
                    if (!value) {
                        this.$message({
                            message: rule[0].message,
                            type: 'warning'
                        })
                        return false;
                    }
                }
            }
            return true;
        },

        saveLaws() {
            // 验证表单
            if (!this.isValidate(this.lawsForm)) {
                return
            }

            // 向后端传输数据
            request.post('/laws/edit', this.lawsForm).then(res => {
                if (res.code === '200' && res.data === true) {
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    })
                    this.closeAddLaws()
                    // 更新数据
                    this.load()
                } else if (res.code === '500') {
                    this.$message({
                        message: res.msg,
                        type: 'error'
                    })
                } else {
                    this.$message({
                        message: '保存失败',
                        type: 'error'
                    })
                }
            })
        },
        // 删除
        deleteRoleData(id) {
            this.$confirm('确定删除吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get(`/laws/delete/${id}`).then(res => {
                    if (res.code === '200') {
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        })
                        // 更新数据
                        this.load()
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                })
            }).catch(() => {
                this.$message({
                    message: '已取消删除',
                    type: 'info'
                })
            })
        },
        // 编辑
        editRoleData(row) {
            this.isEdit = true;
            this.lawsForm = { ...row };
            this.dialogFormVisible = true
        },
    }
}
</script>

<style scoped>
#roleSpan {
    color: black;
    text-decoration: none;
}

/*   外框架   */
.framework1 {
    height: calc(100vh - 88px);
    width: calc(100vh - 200px);
    margin-left: 8px;
    border: solid 1px #D3D3D3;
}

/*   内框架   */
.framework2 {
    height: calc(100vh - 92px);
    border: solid 1px #D3D3D3;
}

/*   表格大标题   */
.header {
    font-size: 16px;
    font-weight: bold;
    padding: 4px 20px;
    background-color: #D3D3D3;
}

/*   表格按键组   */
.button_group {
    padding: 4px 10px;
    background-color: #DDDDDD;
}

/*   表格分页处   */
.footer {
    padding: 4px 10px;
    background-color: #f4f3f9;
}


.formatted-text {
    text-align: left;
    white-space: pre-wrap;
}

.law-type-select-style {
    display: block;
    width: 100% !important;
}
</style>
